<!--
 * @Author: byron
 * @Date: 2021-10-22 21:16:26
 * @LastEditTime: 2022-05-09 12:11:56
-->
<template>
    <div>
        <page-header title="文章列表" describe="">
            <div
                class="search-warp"
                style="display: flex; justify-content: space-between"
            >
                <div class="search-input" style="width: 300px">
                    <a-input-search
                        v-model:value="searchValue"
                        placeholder="搜索内容"
                        size="default"
                        @search="onSearch"
                    />
                </div>

                <a-button
                    type="primary"
                    @click="showAddModal"
                    style="margin-left: 30px"
                    >添加文章</a-button
                >
            </div>
        </page-header>
        <page-layout>
            <a-card>
                <a-list
                    item-layout="vertical"
                    size="large"
                    :pagination="pagination"
                    :data-source="data"
                >
                    <template v-slot:renderItem="{ item }">
                        <a-list-item key="item.title">
                            <template v-slot:actions>
                                <span v-for="{ type } in actions" :key="type">
                                    <component
                                        v-bind:is="type"
                                        style="margin-right: 8px"
                                    />
                                    {{ item.action[type] }}
                                </span>
                            </template>
                            <template v-slot:extra>
                                <img
                                    width="272"
                                    alt="logo"
                                    src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png"
                                />
                            </template>
                            <a-list-item-meta :description="item.description">
                                <template v-slot:title>
                                    <a :href="item.href" target="_blank">{{
                                        item.title
                                    }}</a>
                                </template>
                                <template v-slot:avatar>
                                    <a-avatar :src="item.avatar"
                                /></template>
                            </a-list-item-meta>
                            <div class="art-content">{{ item.summary }}</div>
                            <div class="footer-switch" style="margin: 16px 0">
                                <span style="margin-right: 16px">
                                    <a-switch
                                        v-model:checked="item.weight"
                                        checked-children="置顶"
                                        un-checked-children="取消置顶"
                                    />
                                </span>

                                <a-switch
                                    v-model:checked="item.status"
                                    checked-children="显示"
                                    un-checked-children="隐藏"
                                />
                            </div>
                            <div class="footer-btn">
                                <a-button
                                    type="primary"
                                    size="default"
                                    style="margin-right: 5px"
                                    @click="showModal(item.id)"
                                    >编辑</a-button
                                >

                                <a-button
                                    danger
                                    size="default"
                                    @click="delArt(item.id)"
                                    >删除</a-button
                                >
                            </div>
                        </a-list-item>
                    </template>
                </a-list>
                <a-modal
                    v-model:visible="visible"
                    title="编辑文章"
                    :confirm-loading="confirmLoading"
                    centered
                    @ok="handleOk"
                >
                    <a-form
                        ref="ruleForm"
                        :model="form"
                        :rules="rules"
                        :label-col="labelCol"
                        :wrapper-col="wrapperCol"
                    >
                        <a-form-item ref="name" label="标题" name="title">
                            <a-input
                                v-model:value="form.title"
                                placeholder="输入文章标题"
                            />
                        </a-form-item>

                        <a-form-item label="内容" name="content">
                            <a-textarea
                                placeholder="输入文章内容"
                                v-model:value="form.content"
                                :autoSize="{ minRows: 8, maxRows: 20 }"
                            />
                        </a-form-item>

                        <a-form-item label="标签" name="tagId">
                            <a-select
                                v-model:value="form.tagsId"
                                size="large"
                                style="width: 200px"
                                :options="options.data"
                                @change="handleChange"
                            ></a-select>
                        </a-form-item>

                        <a-form-item label="启用" name="status">
                            <a-switch v-model:checked="form.status" />
                        </a-form-item>

                        <a-form-item label="描述" name="desc">
                            <a-textarea
                                placeholder="请输入文章描述，若未输入则自动设置文章的前225字符为摘要"
                                v-model:value="form.desc"
                            />
                        </a-form-item>
                    </a-form>
                </a-modal>
                <!-- 添加文章对话框 -->
                <a-modal
                    v-model:visible="addvisible"
                    title="添加文章"
                    :confirm-loading="confirmLoading"
                    okText="提交"
                    cancelText="取消"
                    @ok="addBlogBtn"
                    wrap-class-name="full-modal"
                >
                    <a-form
                        ref="ruleForm"
                        :model="form"
                        :rules="rules"
                        :label-col="labelCol"
                        :wrapper-col="wrapperCol"
                    >
                        <a-form-item ref="name" label="标题" name="title">
                            <a-input
                                v-model:value="form.title"
                                placeholder="输入文章标题"
                            />
                        </a-form-item>

                        <a-form-item ref="" label="" name="">
                            <v-md-editor
                                left-toolbar="undo redo | emoji"
                                v-model="form.body.content"
                                height="400px"
                            ></v-md-editor>
                        </a-form-item>

                        <a-form-item label="分类">
                            <a-radio-group v-model:value="form.categoryId">
                                <a-radio-button
                                    :value="item.id"
                                    v-for="item in categoryList"
                                    :key="item.id"
                                >
                                    {{ item.name }}
                                </a-radio-button>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="标签">
                            <a-checkable-tag
                                v-for="(item, index) in tagList"
                                :key="index"
                                v-model:checked="item.value"
                                @change="handleChange(item.id, item.value)"
                                >{{ item.name }}</a-checkable-tag
                            >

                            <a-input
                                v-if="inputVisible"
                                ref="TagInputRef"
                                v-model:value="inputValue"
                                type="text"
                                size="small"
                                :style="{ width: '78px' }"
                                @keyup.enter="handleInputConfirm"
                            />
                            <a-tag
                                v-else
                                style="background: #fff; border-style: dashed"
                                @click="showInput"
                            >
                                <plus-outlined />
                                New Tag
                            </a-tag>
                        </a-form-item>

                        <a-form-item label="启用" name="status">
                            <a-switch v-model:checked="form.status" />
                        </a-form-item>

                        <a-form-item label="描述" name="desc">
                            <a-textarea
                                placeholder="请输入文章描述，若未输入则自动设置文章的前225字符为摘要"
                                v-model:value="form.summary"
                            />
                        </a-form-item>
                        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                            <div class="reset_btn">
                                <a-button type="dashed" block @click="resetForm"
                                    >重置</a-button
                                >
                            </div>
                        </a-form-item>
                    </a-form>
                </a-modal>
            </a-card>
        </page-layout>
    </div>
</template>
<script>
import {
    StarOutlined,
    LikeOutlined,
    MessageOutlined,
} from '@ant-design/icons-vue'
import VueMarkdownEditor, { xss } from '@kangc/v-md-editor'

import { subString } from '@/tools/bussiness.js'
import {
    getArticles,
    delArticle,
    getCategory,
    getTags,
    editArticle,
    addArticles,
    addTag,
} from '@/api/index'

import { ref, nextTick, reactive, toRefs, createVNode } from 'vue'

import { message, Modal } from 'ant-design-vue'

import { createArticle } from '../../tools/bussiness'

import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

export default {
    components: {
        StarOutlined,
        LikeOutlined,
        MessageOutlined,
        ExclamationCircleOutlined,
    },
    setup() {
        const TagInputRef = ref()
        const Tagstate = reactive({
            inputVisible: false,
            inputValue: '',
        })

        const showInput = () => {
            Tagstate.inputVisible = true
            nextTick(() => {
                TagInputRef.value.focus()
            })
        }

        const handleInputConfirm = async () => {
            const inputValue = Tagstate.inputValue
            if (inputValue.trim() != '') {
                const data = {
                    tagName: inputValue,
                    status: 1,
                }
                const { data: r } = await addTag(data)
                console.log(r)
                if (r.code == 200) {
                    message.success('添加标签成功')
                    Tagstate.inputVisible = false
                    getTag()
                } else {
                    message.error(r.msg)
                }
            } else {
                Tagstate.inputVisible = false
            }
        }
        const contentBody = ref('')
        const editID = ref()
        const addvisible = ref(false)
        const tagList = ref([])
        const categoryList = ref([])

        const form = ref({
            title: '',
            body: {
                content: '',
                contentHtml: 'html',
            },
            status: 1,
            summary: '',
            categoryId: 1,
            tagsId: [],
            modifiedBy: '王灿',
        })

        const getTag = async () => {
            const r = await getTags()
            const { data } = r
            console.log('data', data)
            if (data.data.length > 0) {
                tagList.value = data.data.map((ele) => {
                    return {
                        id: ele.id,
                        name: ele.tagName,
                        value: false,
                    }
                })
            }
        }
        const _getCategory = async () => {
            const { data: r } = await getCategory()
            categoryList.value = r.data.map((e) => {
                console.log('dadsads', e.id)
                const object = {
                    id: e.id,
                    name: e.categoryName,
                }
                console.log(object)
                return object
            })
        }
        const visible = ref(false)
        const confirmLoading = ref(false)
        const data = ref([])

        /**
         * 添加文章
         */

        const showAddModal = () => {
            getTag()
            _getCategory()
            addvisible.value = true
        }

        const pagination = {
            onChange: (page) => {
                message.success(`切换成功，当前页码${page}`)
            },
            pageSize: 5,
        }
        const actions = [
            {
                type: 'StarOutlined',
            },
            {
                type: 'LikeOutlined',
            },
            {
                type: 'MessageOutlined',
            },
        ]

        const getData = function (callback) {
            getArticles().then((reponse) => {
                callback(reponse.data.data)
            })
        }
        getData((res) => {
            data.value = res.blog.map((e) => {
                return createArticle(e)
            })
        })

        // 添加标签
        const handleChange = (id, value) => {
            if (value) {
                form.value.tagsId.push(id)
            } else {
                const index = form.value.tagsId.indexOf(id)
                form.value.tagsId.splice(index, 1)
            }
        }

        /**
         * 删除文章
         */
        const delArt = (id) => {
            Modal.confirm({
                title: '确认删除？',
                icon: createVNode(ExclamationCircleOutlined),
                content: '删除之后将无法找回，请谨慎删除',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    const { data: r } = await delArticle(id)
                    const { code, msg } = r
                    if (code != 200) {
                        message.error(msg)
                        return
                    }
                    message.success('删除文章成功')
                    getData((res) => {
                        data.value = res.blog.map((e) => {
                            return createArticle(e)
                        })
                    })
                },
            })
        }
        const showModal = (id) => {
            getTag().then(() => {
                visible.value = true
            })
            editID.value = id
        }
        const handleOk = async () => {
            confirmLoading.value = true
            const r = await editArticle(editID.value, form.value)
            const { code, msg } = r
            if (code != 200) {
                message.error(msg)
                confirmLoading.value = false
                return
            }
            message.success('编辑文章成功')
            visible.value = false
            confirmLoading.value = false
            getData((res) => {
                data.value = res.data.results.map((e) => {
                    return createArticle(e)
                })
            })
        }
        const addBlogBtn = async () => {
            form.value.body.contentHtml = xss.process(
                VueMarkdownEditor.vMdParser.themeConfig.markdownParser.render(
                    form.value.body.content
                )
            )
            if (!form.value.summary.trim()) {
                form.value.summary = subString(form.value.body.content, 0, 225)
            }
            const r = await addArticles(form.value)
            const { code, msg } = r.data
            if (code == 200) {
                message.success('添加文章成功')
                addvisible.value = false
                form.value = {
                    title: '',
                    body: {
                        content: '',
                        contentHtml: 'html',
                    },
                    status: 1,
                    summary: '',
                    categoryId: 1,
                    tagsId: [],
                    modifiedBy: '王灿',
                }
                getData((res) => {
                    data.value = res.blog.map((e) => {
                        return createArticle(e)
                    })
                })
            } else {
                message.error(msg)
            }
        }

        /**
         * 搜索功能
         */
        const searchValue = ref()
        const onSearch = () => {}

        return {
            editID,
            data,
            pagination,
            actions,
            delArt,
            visible,
            confirmLoading,
            showModal,
            handleOk,
            form,
            tagList,
            showAddModal,
            addvisible,
            searchValue,
            onSearch,
            handleChange,
            contentBody,
            addBlogBtn,
            checked1: ref(false),
            categoryList,
            ...toRefs(Tagstate),
            showInput,
            TagInputRef,
            handleInputConfirm,
        }
    },
}
</script>
<style lang="less">
.art-content {
    /* height: 100px; */
    display: -webkit-box;
    line-height: 2;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.ant-list-item-extra {
    display: flex;
    align-items: center;
}

.reset_btn {
    display: flex;
    justify-content: center;
    align-items: center;
}

.ant-form-item {
    justify-content: center;
}

.ant-col-offset-4 {
    margin-left: 0px;
}

.footer-btn {
    margin-top: 10px;
    margin-right: 5px;
}

.full-modal {
    .ant-modal {
        top: 0;
        padding-bottom: 0;
        margin: 0;
    }

    .ant-modal-content {
        display: flex;
        flex-direction: column;
        width: 100vw;
        height: 100vh;
        overflow-x: hidden;
    }

    .ant-modal-body {
        flex: 1;
    }
}
</style>
